<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

class User extends Common
{

	public function _initialize()
    {   
        parent::_initialize();
    }

    public function login(){
        return $this->fetch();
    }

    public function send_sms(){
        $phone = input('mobile');

        $where['phone'] = ['eq',$phone];
        if(db('user')->where($where)->find()){
            return json(['code'=>100,'msg'=>'手机号已经被注册']);
        }else{
            $code = GetRandCode();
            session_start();
            $_SESSION['rendcode'] = $code;
            $send = alisms($phone,$code);
            if($send['Code'] == 'OK'){
                return json(['code'=>200,'msg'=>'发送成功']);
            }else{
                return json(['code'=>100,'msg'=>'验证码发送失败,请稍后再试！']);
            }
        }
       
    }
    //过期删除存储的验证码
    public function remove_code(){
        session_start();
        unset($_SESSION['rendcode']);
    }

    //登录操作
    public function loging(){
        // 登录请求都以post形式
        if(Request::instance()->isPost()){
            // 获取参数
            $account = stripslashes(input('post.account'));
            $password = trim(input('post.password'));
            $keeplogin = input('post.keeplogin');
            if(empty($account) || empty($password)){
                $result['code'] = 201;
                $result['msg'] = '请输入正确的账号和密码';
            }else{
                // 获取到记录
                $time = time();
                //根据邮箱和手机号查询是否存在这个用户
                $l_where['phone'] = ['eq',$account];
                $l_where['nick_name'] = ['eq',$account];
                $userinfo = db('user')->field("u_id,email,nick_name,phone,password,pwd_code,head_img,reg_time,is_lock,lock_time,last_login_time,is_deldete")->whereOr($l_where)->find();
                if(!empty($userinfo) && $userinfo['password'] == md5($password.$userinfo['pwd_code'])){
                    //验证用户是否被后台删除了
                    if($userinfo['is_deldete'] == 2){
                        $result['code'] = 201;
                        $result['msg'] = '此号已被禁用，请联系客服！';//查无此人账号或者密码错误）
                    }else{
                        if($userinfo['is_lock'] == 2 && $time < $userinfo['lock_time']){
                            $result['code'] = 202 ;
                            $result['msg'] = "账号已经锁定". date("Y/m/d H:i:s",$userinfo['lock_time']) ."后解锁" ;
                        }else{
                            $md_five_uid_reg_time = md5($userinfo['email'].$userinfo['reg_time']);
                            /*  记录 session{ 邮箱 + 名称 + 登录code[md5(邮箱+注册时间)]} */
                            Session::set('email',$userinfo['email']);
                            Session::set('nick_name',$userinfo['nick_name']);
                            Session::set('phone',$userinfo['phone']);
                            Session::set('login_code',$md_five_uid_reg_time);
                            //新增
                            Session::set('u_id',$userinfo['u_id']);
                            //如果没有头像 默认一个
                            if(!empty($userinfo['head_img'])){
                                Session::set('headimg',$userinfo['head_img']);
                            }else{
                                Session::set('headimg','/static/index/picture/icon.png');
                            }
                            
                            $save['last_login_time'] = $time;
                            $save['last_login_ip'] = $this->get_real_ip();
                            $save['is_lock'] = 1;
                            $save['user_status'] = 1; //用户登录状态
                            $save['lock_time'] = 0;
                            $save['md_five_uid_reg_time'] = $md_five_uid_reg_time;
                            db('user')->where(" u_id = '".$userinfo['u_id']."' ")->update($save);
                            db('user')->where(" u_id = '".$userinfo['u_id']."' ")->setInc('login_num');
                            $result['code'] = 200;
                            $result['msg'] = '登录成功';
                        }
                    }
                }else{
                    $result['code'] = 201;
                    $result['msg'] = '用户名或密码错误';//查无此人账号或者密码错误）
                }
            }
        }else{
            $result['code'] = 203;
            $result['msg'] = '用户名或密码错误';//不是POST请求
        }
        return json($result);
    }

    public function register(){
        return $this->fetch();
    }

    public function registration(){
        // 注册请求都以post形式
        if(Request::instance()->isPost()){
            
            // $parameter = check_param(array('email','username','password','mobile','code'));
            // if(empty($parameter)){
                $account = stripslashes(input('post.email'));
                $username = stripslashes(input('post.username'));
                $password = trim(input('post.password'));
                $mobile = trim(input('post.mobile'));
                //code 暂未加
                $code = trim(input('post.code'));
                $agreement = input('post.agreement');
                if( empty($account) || empty($username) || empty($password) || empty($mobile) || empty($code)) {
                    $result['code'] = 201;
                    $result['msg'] = '请将信息输入完整';//请输入正确的邮箱和密码
                }else{
                    //验证过期
                    session_start();
                    if(empty($_SESSION['rendcode']) || !isset($_SESSION['rendcode'])){
                        $result['code'] = 201;
                        $result['msg'] = '验证码已经过期,请重新发送验证码';
                    }else{
                        //验证输入验证码是否正确
                        if($_SESSION['rendcode'] != $code){
                            $result['code'] = 201;
                            $result['msg'] = '验证码输入错误';
                        }else{
                            //验证邮箱是否注册
                            $where_email['email'] = ['eq',$account];
                            if(db('user')->where($where_email)->find()){
                                $result['code'] = 201;
                                $result['msg'] = '邮箱已经被占用';
                            }else{
                                //验证用户名时候占用
                                $where_name['nick_name'] = ['eq',$username];
                                if(db('user')->where($where_name)->find()){
                                    $result['code'] = 201;
                                    $result['msg'] = '用户名已经被占用';
                                }else{
                                    //验证手机号是否注册
                                    $where_phone['phone'] = ['eq',$mobile];
                                    if(db('user')->where($where_phone)->find()){
                                        $result['code'] = 201;
                                        $result['msg'] = '手机号已经被注册';
                                    }else{
                                        //插入数据
                                        $round = rand(100000,999999);
                                        $time = time();
                                        $md_five_uid_reg_time = md5($account.$time);
                                        $add_data = array(
                                            'email' => $account,
                                            'nick_name' => $username,
                                            'head_img' => '/static/index/picture/icon.png',
                                            'phone' => $mobile,
                                            'signature'=> '这家伙很懒，什么也没写！',
                                            'password' => md5($password . $round),
                                            'pwd_code' => $round,
                                            'reg_time' => $time,
                                            'reg_ip' => $this->get_real_ip(),
                                            'last_login_time' => $time,
                                            'last_login_ip' => $this->get_real_ip(),
                                            'is_lock' => 1,
                                            'sex'=>1,
                                            'lock_time' => 0,
                                            'oauth' => 1,
                                            'md_five_uid_reg_time' => md5($md_five_uid_reg_time.$time),
                                            
                                        );
                                        Session::set('email',$account);
                                        Session::set('nick_name',$username);
                                        Session::set('phone',$mobile);
                                        Session::set('login_code',$md_five_uid_reg_time);
                                        //如果没有头像 默认一个
                                        Session::set('headimg','/static/index/picture/icon.png');
                                        //新增
                                        db('user')->insert($add_data);
                                        $u_id = db('user')->getLastInsID();
                                        Session::set('u_id',$u_id);
                                        
                                        $result['code'] = 200;
                                        $result['msg'] = 'Login success~';

                                    }
                                }
                            }
                        }
                    }
                }
            // }else{
            //     $result['code'] = 202;
            //     $result['msg'] = '缺少参数'; }
            // }
        }else{
            $result['code'] = 203;
            $result['msg'] = '用户名或密码错误';//不是POST请求
        }
        return json($result);
    }

    /* 获取用户注册 ip*/
    function get_real_ip()
    {
        $ip=FALSE;
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    /* 退出 */
    public function logout(){
        session_start();
        if(isset($_SESSION['think']['u_id']) && !empty($_SESSION['think']['u_id'])){
            $data['user_status'] = '2';//离线
            $where['u_id'] = ['eq',$_SESSION['think']['u_id']];
            db('user')->where($where)->update($data);
        }
        //清除登录存储session
        // Session::clear();
        unset($_SESSION['think']['u_id']);
        unset($_SESSION['think']['email']);
        unset($_SESSION['think']['nick_name']);
        unset($_SESSION['think']['phone']);
        unset($_SESSION['think']['login_code']);
        unset($_SESSION['think']['headimg']);
        $this->redirect('/index');
    }

    /* 用户协议 */
    public function agreement(){
        $query = db('article_page')->where('id',4)->find();

        $this->assign('page',$query);
        return $this->fetch();
    }
}
